import 'package:fl_chart/fl_chart.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:sleep/config.dart';
import 'package:sleep/provider/db_provider.dart';
import 'package:sleep/provider/wave_deatil_provider/wave_provider.dart';
import 'package:sleep/single/analyze/pluse_analyze.dart';
import 'package:sleep/single/wave_show_model.dart';

class PulseDetailWave {
  final String bpm;
  final String hrv;
  final String si;
  final String pwv;

  final List<FlSpot> bpmSpots;
  final List<FlSpot> hrvSpots;
  final List<FlSpot> siSpots;
  final List<FlSpot> pwvSpots;

  PulseDetailWave(
      {required this.bpm,
      required this.hrv,
      required this.si,
      required this.pwv,
      required this.bpmSpots,
      required this.siSpots,
      required this.pwvSpots,
      required this.hrvSpots});
}

final pulseDetailProvider = Provider<PulseDetailWave>((ref) {
  final pulse = ref.watch(pulseProvider);
  final analyze = pulse.analyze as pulseAnalyze;
  final person = ref.read(dbProvider).getPerson(kSleepPerson);
  PluseShowModel? wave = analyze.wave;
  List<PluseShowModel> waves = analyze.waves;

  final bpm = wave?.bpm.toStringAsFixed(0) ?? "-";

  final si = (wave?.pPT != null ? (person?.height ?? 0) / wave!.pPT : null)
          ?.toStringAsFixed(2) ??
      "-";

  final pwv = (wave?.rWTT != null ? 1.6 * (person?.l ?? 0) / wave!.rWTT : null)
          ?.toStringAsFixed(2) ??
      "-";

  final List<FlSpot> bpmSpots = [];
  final List<FlSpot> hrvSpots = [];
  final List<FlSpot> siSpots = [];
  final List<FlSpot> pwvSpots = [];

  for (int i = 0; i < kDetialShowLengh; i++) {
    final index = waves.length - i - 1;
    if (index > 0) {
      final current = waves[index];
      final bpm = current.bpm;

      final x = (kDetialShowLengh - i).toDouble();
      final si = (person?.height ?? 0) / current.pPT;
      final pwv = 1.6 * (person?.l ?? 0) / current.rWTT;
      bpmSpots.add(FlSpot(x, bpm));
      hrvSpots.add(FlSpot(x, current.hrv ?? 0));
      siSpots.add(FlSpot(x, si.toDouble()));
      pwvSpots.add(FlSpot(x, pwv.toDouble()));
    }
  }
  final hrv = wave?.hrv?.toStringAsFixed(2) ?? "-";

  return PulseDetailWave(
    bpmSpots: bpmSpots,
    hrvSpots: hrvSpots,
    siSpots: siSpots,
    pwvSpots: pwvSpots,
    pwv: pwv,
    bpm: bpm,
    hrv: hrv,
    si: si,
  );
});
